<template>
  <div class="right-main">
    <div class="tob-bar">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/business/list' }">商保方案</el-breadcrumb-item>
        <el-breadcrumb-item>编辑</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="mainContainer addBusinessPage">
      <!-- 添加商保方案表单 -->
      <div class="customform shebaoform">
        <el-form
          :inline="true"
          :rules="rules"
          :model="product"
          label-width="130px"
          label-position="left"
          ref="product"
        >
          <div class="el-form--inline">
            <el-form-item label="方案编号" prop="productCode">
              <el-input v-model="product.productCode"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="product.name"></el-input>
            </el-form-item>
            <el-form-item label="公司名称">
              <CompanySelect :p_value.sync="product.optrCompId" :p_name.sync="product.optrCompName"></CompanySelect>
            </el-form-item>
          </div>
          <div class="el-form--inline">
            <el-form-item label="最小年龄" prop="maleAgeMin">
              <el-input v-model="product.maleAgeMin" type="number"></el-input>
            </el-form-item>
            <el-form-item label="男最大年龄" prop="maleAgeMax">
              <el-input v-model="product.maleAgeMax" type="number"></el-input>
            </el-form-item>
            <el-form-item label="女最大年龄" prop="femaleAgeMax">
              <el-input v-model="product.femaleAgeMax" type="number"></el-input>
            </el-form-item>
          </div>
          <div class="el-form--inline">
            <el-form-item label="保险周期">
              <el-select v-model="product.cycleCode" placeholder>
                <el-option label="年" value="1"></el-option>
                <el-option label="月" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合同期限" prop="date">
              <el-date-picker
                class="custom-date-picker"
                v-model="product.date"
                type="daterange"
                align="right"
                format="yyyy.MM.dd"
                value-format="yyyy.MM.dd"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <!-- <el-form-item label="状态">
              <el-switch
                v-model="product.used"
                active-color="#ff8b2b"
                inactive-color="#cccccc"
                :active-value="Number(1)"
                :inactive-value="Number(0)"
              ></el-switch>
            </el-form-item> -->
          </div>
          <div class="el-form--inline">
            <el-form-item label="是否启用">
              <el-switch
                      v-model="product.status"
                      active-text="启用"
                      inactive-text="禁用"
                      :active-value="Number(0)"
                      :inactive-value="Number(1)"
              >
              </el-switch>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 添加商保方案表单结束 -->
    </div>

    <div class="mainContainer m-t20">
      <!-- 表格 -->
      <div class="zy-form my-table">
        <template>
          <el-table :data="items">
            <el-table-column label="项目名称" width="300">
              <template slot-scope="scope">
                <el-input v-model="scope.row.itemName" placeholder></el-input>
              </template>
            </el-table-column>
            <el-table-column label="项目值">
              <template slot-scope="scope">
                <el-tag
                  class="product-value"
                  :key="tag"
                  v-for="tag in scope.row.dynamicTags"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row.dynamicTags,tag)"
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  placeholder="回车键确认"
                  ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" @click="showInput(scope.row)">
                  <i class="iconfont iconadd"></i> 添加值
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot="header">
                <el-button class="fr" size="small" @click="addPrice">
                  <i class="iconfont iconbook"></i> 价格清单
                </el-button>
              </template>
              <template>
                <el-button class="fr" size="small" @click="deletRow">
                  <i class="iconfont icondelet"></i> 删除项目
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="clearfix">
          <el-button class="fr table-add-row" @click="addRow" size="small">
            <i class="iconfont iconadd"></i> 添加项目
          </el-button>
        </div>
      </div>
      <!-- 表格结束 -->
    </div>

    <!-- 保险责任 -->
    <div class="mainContainer m-t20">
      <h1 class="com-title">保险责任</h1>
      <!-- bidirectional data binding（双向数据绑定） -->
      <quill-editor v-model="product.terms" ref="myQuillEditor" :options="editorOption"></quill-editor>
    </div>
    <!-- 保险责任结束 -->

    <div class="page-form-btn">
      <el-button @click="$router.go(-1);">取消</el-button>
      <el-button type="primary" @click="save('product')">保存</el-button>
    </div>
  </div>
</template>

<script>
import Http from "../../libs/http.js";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";
import CompanySelect from "../../components/CompanySelect";
import dataDictSelect from "../../components/DataDictSelect";

const titleConfig = [
  { Choice: ".ql-bold", title: "加粗" },
  { Choice: ".ql-italic", title: "斜体" },
  { Choice: ".ql-underline", title: "下划线" },
  { Choice: ".ql-header", title: "段落格式" },
  { Choice: ".ql-strike", title: "删除线" },
  { Choice: ".ql-blockquote", title: "块引用" },
  { Choice: ".ql-code", title: "插入代码" },
  { Choice: ".ql-code-block", title: "插入代码段" },
  { Choice: ".ql-font", title: "字体" },
  { Choice: ".ql-size", title: "字体大小" },
  { Choice: '.ql-list[value="ordered"]', title: "编号列表" },
  { Choice: '.ql-list[value="bullet"]', title: "项目列表" },
  { Choice: ".ql-direction", title: "文本方向" },
  { Choice: '.ql-header[value="1"]', title: "h1" },
  { Choice: '.ql-header[value="2"]', title: "h2" },
  { Choice: ".ql-align", title: "对齐方式" },
  { Choice: ".ql-color", title: "字体颜色" },
  { Choice: ".ql-background", title: "背景颜色" },
  { Choice: ".ql-image", title: "图像" },
  { Choice: ".ql-video", title: "视频" },
  { Choice: ".ql-link", title: "添加链接" },
  { Choice: ".ql-formula", title: "插入公式" },
  { Choice: ".ql-clean", title: "清除字体格式" },
  { Choice: '.ql-script[value="sub"]', title: "下标" },
  { Choice: '.ql-script[value="super"]', title: "上标" },
  { Choice: '.ql-indent[value="-1"]', title: "向左缩进" },
  { Choice: '.ql-indent[value="+1"]', title: "向右缩进" },
  { Choice: ".ql-header .ql-picker-label", title: "标题大小" },
  { Choice: '.ql-header .ql-picker-item[data-value="1"]', title: "标题一" },
  { Choice: '.ql-header .ql-picker-item[data-value="2"]', title: "标题二" },
  { Choice: '.ql-header .ql-picker-item[data-value="3"]', title: "标题三" },
  { Choice: '.ql-header .ql-picker-item[data-value="4"]', title: "标题四" },
  { Choice: '.ql-header .ql-picker-item[data-value="5"]', title: "标题五" },
  { Choice: '.ql-header .ql-picker-item[data-value="6"]', title: "标题六" },
  { Choice: ".ql-header .ql-picker-item:last-child", title: "标准" },
  { Choice: '.ql-size .ql-picker-item[data-value="small"]', title: "小号" },
  { Choice: '.ql-size .ql-picker-item[data-value="large"]', title: "大号" },
  { Choice: '.ql-size .ql-picker-item[data-value="huge"]', title: "超大号" },
  { Choice: ".ql-size .ql-picker-item:nth-child(2)", title: "标准" },
  { Choice: ".ql-align .ql-picker-item:first-child", title: "居左对齐" },
  {
    Choice: '.ql-align .ql-picker-item[data-value="center"]',
    title: "居中对齐"
  },
  {
    Choice: '.ql-align .ql-picker-item[data-value="right"]',
    title: "居右对齐"
  },
  {
    Choice: '.ql-align .ql-picker-item[data-value="justify"]',
    title: "两端对齐"
  }
];
export default {
  name: "addBusiness",
  watch: {},
  components: {
    quillEditor,
    CompanySelect,
    dataDictSelect
  },
  data() {
    var checkAge = (rule, value, callback) => {
      if (value) {
        if (Number.isInteger(Number(value)) && Number(value) > 0) {
          callback();
        } else {
          callback(new Error("请输入有效年龄"));
        }
      }
    };
    return {
      productId: this.$route.query.id,
      // 编辑器
      content: "",
      editorOption: {
        // some quill options
        placeholder: "请输入内容"
      },
      // 添加公积金表单
      product: {
        productCode: "",
        optrCompId: "",
        optrCompName: "",
        optrCompCode: "",
        startDate: "",
        endDate: "",
        cycleCode: "",
        maleAgeMin: "",
        maleAgeMax: "",
        femaleAgeMin: "",
        femaleAgeMax: "",
        date: [],
        status:0,
        terms: ""
      },
      //项目值
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      // 表格
      items: [
        {
          inputVisible: false
        }
      ],
      // 必填项目
      rules: {
        productCode: [
          { required: true, message: "请输入方案编号", trigger: "blur" },
          { max: 255, message: "不能超过255个字符", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入方案名称", trigger: "blur" },
          { max: 255, message: "不能超过255个字符", trigger: "blur" }
        ],
        maleAgeMin: [{ validator: checkAge, trigger: "blur" }],
        maleAgeMax: [{ validator: checkAge, trigger: "blur" }],
        femaleAgeMax: [{ validator: checkAge, trigger: "blur" }],
        value2: [
          { required: true, message: "请选择服务公司", trigger: "change" }
        ],
        date: [
          { required: true, message: "请选择合同期限", trigger: "change" }
        ],
        value4: [
          { required: true, message: "请输入方案名称", trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    autotip: {
      document.getElementsByClassName("ql-editor")[0].dataset.placeholder = "";
      for (let item of titleConfig) {
        let tip = document.querySelector(".quill-editor " + item.Choice);
        if (!tip) continue;
        tip.setAttribute("title", item.title);
      }
    }
  },
  created() {
    this.getDetail();
  },
  methods: {
    getDetail: function() {
      Http.api.get("/insure/" + this.$route.query.id).then(res => {
        this.product = res.data.productDto;
        this.items = new Array();
        for (let i in res.data.items) {
          let d = res.data.items[i];
          d.dynamicTags = d.itemValues.split(",");
          d.inputVisible = false;
          this.items.push(d);
        }
        this.product.date = new Array();
        this.product.date.push(this.product.startDate);
        this.product.date.push(this.product.endDate);
      });
    },
    // 保存
    save() {
      this.$refs["product"].validate(valid => {
        console.log(valid);
        this.items.forEach(item => {
          item.itemValues = item.dynamicTags.join(",");
        });
        if (valid) {
          this.product.startDate = this.product.date[0];
          this.product.endDate = this.product.date[1];
          this.product.femaleAgeMin = this.product.maleAgeMin;
          Http.api
            .post("insure", {
              items: this.items,
              productDto: this.product
            })
            .then(res => {
              console.log(res);
              this.endAddRow(res.data.id);
            });
        } else {
        }
      });
    },
    //价格清单
    addPrice() {
      console.log(this.productId);
      this.$router.push({
        path: "/business/addPrice",
        query: { id: this.productId }
      });
    },
    endAddRow(id) {
      this.$confirm("方案添加成功，是否需要编辑价格清单", "提示", {
        confirmButtonText: "去编辑",
        cancelButtonText: "不去编辑",
        type: "warning",
        customClass: "custom-modal",
        iconClass: "no-icon",
        center: true
      })
        .then(() => {
          this.$router.push({
            path: "/business/addPrice",
            query: { id: this.productId }
          });
        })
        .catch(() => {
          this.$router.push({ path: "/business/list" });
        });
    },
    addRow() {
      if (this.items.length == 0) {
        this.items.push({
          itemName: "项目",
          dynamicTags: [],
          itemValues: "",
          inputVisible: false,
          inputValue: ""
        });
        return;
      }
      let last = this.items[this.items.length - 1];
      if (last.itemName) {
        this.items.push({
          itemName: "项目",
          dynamicTags: [],
          itemValues: "",
          inputVisible: false,
          inputValue: ""
        });
      } else {
        this.$message("请完善项目信息");
      }
    },
    //项目值
    handleClose(tages, tag) {
      tages.splice(tages.indexOf(tag), 1);
    },
    showInput(d) {
      d.inputVisible = true;
      this.$nextTick(_ => {
        // this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm(d) {
      let inputValue = d.inputValue;
      var s = false;
      d.dynamicTags.forEach(name => {
        if (name === inputValue) {
          s = true;
        }
      });
      if (s) {
        this.$message("项目值不能相同");
        return;
      }
      if (inputValue) {
        d.dynamicTags.push(inputValue);
      }
      d.inputVisible = false;
      d.inputValue = "";
    },
    // 删除项目
    deletRow(index) {
      this.items.splice(index, 1);
    }
  }
};
</script>
